#pragma once
#include <unordered_map>
#include <string>
#include <mutex>
#include <chrono>
#include <random>

namespace ns_session {
    class SessionManager {
    private:
        std::unordered_map<std::string, std::string> session_map_;  // session_id -> username
        std::mutex mtx_;
        // 生成随机会话ID
        std::string GenerateSessionId() {
            std::string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            std::string session_id;
            std::random_device rd;
            std::mt19937 gen(rd());
            std::uniform_int_distribution<> dis(0, chars.size() - 1);
            for (int i = 0; i < 32; ++i) {  // 32位随机字符串
                session_id += chars[dis(gen)];
            }
            return session_id;
        }
    public:
        // 创建会话（返回session_id）
        std::string Create(const std::string& username) {
            std::lock_guard<std::mutex> lock(mtx_);
            std::string session_id = GenerateSessionId();
            session_map_[session_id] = username;
            return session_id;
        }
        // 验证会话并获取用户名
        bool Get(const std::string& session_id, std::string* username) {
            std::lock_guard<std::mutex> lock(mtx_);
            auto it = session_map_.find(session_id);
            if (it == session_map_.end()) {
                return false;
            }
            *username = it->second;
            return true;
        }
        // 销毁会话（注销）
        void Destroy(const std::string& session_id) {
            std::lock_guard<std::mutex> lock(mtx_);
            session_map_.erase(session_id);
        }
    };
}